package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDtoListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Luckyh
 * @since 2022-01-25
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        // 写法1：JDK8+ ,不用额外写一个DemoDataListener
        // since: 3.0.0-beta1
//        String fileName = "demo" + File.separator + "demo.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        // new ExcelDictDtoListener(dataList -> {
        //            for (ExcelDictDTO demoData : dataList) {
        //                log.info("读取到一条数据{}", JSON.toJSONString(demoData));
        //            }
        //        })

        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDtoListener(dictMapper)).sheet().doRead();
        log.info("Excel 导入成功");
    }

    @Override
    public List<ExcelDictDTO> listDictData() {

        List<Dict> list = dictMapper.selectList(null);
        ArrayList<ExcelDictDTO> excelDictDTOList = new ArrayList<>(list.size());
        list.forEach(dict -> {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            // 将list中的对象属性拷贝到excelDictDTO中对应的属性里面
            BeanUtils.copyProperties(dict, excelDictDTO);
            excelDictDTOList.add(excelDictDTO);
        });
        return excelDictDTOList;
    }

    @Override
    public List<Dict> listByParentId(long parentId) {

        try {
            // 先从redis缓存当中去查询，如果查询不到，在从数据库当中去查询
            // 异常处理

            List<Dict> dictList = (List<Dict>)redisTemplate.opsForValue().get("srb:core:dict" + parentId);
            if (dictList != null){
                log.info("将数据redis当中取出");
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis 服务器异常:"+ ExceptionUtils.getStackTrace(e));
        }

        log.info("从数据中取出数据");
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        List<Dict> selectList = baseMapper.selectList(queryWrapper);

        selectList.forEach(dict -> {
            boolean hasChildren = hasChildren(dict.getId());

            dict.setHasChildren(hasChildren);
        });

        log.info("将数据存入redis当中");
        redisTemplate.opsForValue().set("srb:core:dict"+parentId,selectList,5, TimeUnit.MINUTES);

        return selectList;
    }

    private boolean hasChildren(Long id){
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
